package com.geely.club.util.openapiclient;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.net.UnknownHostException;

import cn.evun.gap.openapi.client.binding.RopClientException;
import cn.evun.gap.openapi.client.serialize.JsonUtils;
import cn.evun.gap.openapi.client.utils.ClientUtils;

/**
 * Created by mengyangyang on 2015-10-13.
 */
public class Requester {
    private static Context context;

    public static void init(Context c) {
        context = c;
    }

    private static String getJson(Object obj) {
        return JsonUtils.toJSON(obj);
    }

    private static void dealTicketExpire(Exception e, Handler handler) {
        if (e instanceof RopClientException) {
            RopClientException ec = (RopClientException) e;
            try {
                if ("-19".equals(ClientUtils.getErrorCode((RopClientException) e))) {
//                    Intent it = new Intent(context, LoginActivity.class);
//                    it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//                    context.startActivity(it);
                } else if ((ec.getArgs() != null && ec.getArgs().length > 0 && ec.getArgs()[0] instanceof UnknownHostException) ||
                        e.toString().toLowerCase().contains("connection reset by peer)")) {
                    handler.obtainMessage(1, "网络异常，请检查网络设置！").sendToTarget();
                } else {
                    if (e.toString().contains("502") || e.toString().contains("404")) {
                        Message.obtain(handler, 1, "服务器异常，请稍后再试！").sendToTarget();
                    } else if (e.toString().contains("80")) {
                        Message.obtain(handler, 1, "连接超时，网络拥堵或服务器繁忙").sendToTarget();
                    } else {
                        Message.obtain(handler, 1, ClientUtils.getErrorMsg(ec)).sendToTarget();
                    }

                    Log.e(Requester.class.getName(), e.toString());

                }
            } catch (Exception e2) {
                Message.obtain(handler, 1, e2.getMessage()).sendToTarget();
                e2.printStackTrace();
            }

        } else {
            e.printStackTrace();
            handler.obtainMessage(1, e.getMessage()).sendToTarget();
        }
    }
}
